<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/***
* @author     Dennis T. Kaplan
* @copyright  Copyright (c) 2007, PzzAzz LLC
* @link       http://www.pzzazz.com
* @created    Aug 3, 2007
* @since      Aug 3, 2007
* @version    1.0
* @license    GPL
* @package    CodeIgniter
* @subpackage Register
* @filesource
***/

class Register extends Controller 
{
	function setVars()
	{
		$this->tpl['title'] = "Registration";
		$this->tpl['head'] = '';
        $this->tpl['sidebar'] = $this->tm->randomBlock();
	}
	
	function __construct()
	{
		parent::Controller();
        $this->load->model('Tamer_Model', 'tm');
		$this->setVars();
		log_message('debug', "Control Panel->Registration->email: Controler Class Initialized");
        //$this->load->library('profiler');
	}

/*****************************************************************\
|               Register User
\*****************************************************************/	

	function index() 
	{
		if(isset($_POST['Alias']))
		{
			$this->postCheck();
		}
		else
		{
            $this->tpl['countryOptions'] = $this->country_options();
            $this->load->view('control_panel/register', $this->tpl);
		}
	}

	function postCheck()
	{
		log_message('debug', "Register email: Post check");
		$this->load->library('validation');
		$rules['Alias']			= "trim|required|min_length[4]|max_length[20]|xss_clean";
		$rules['eMail']			= "trim|required|valid_email|xss_clean";
		$rules['Country']		= "trim|required|xss_clean";
		$fields['Country']    	= 'Country';
		$this->validation->set_rules($rules);
		$this->validation->set_fields($fields);
		if ($this->validation->run() == FALSE)
		{
            $this->tpl['countryOptions'] = $this->country_options($this->validation->Country);
			$this->load->view('control_panel/register', $this->tpl);
		}
		else
		{
            $email = $this->validation->eMail;
            $alias = $this->validation->Alias;
            $this->db->select('id, eMail')->from('contact_people')->where('eMail', $this->validation->eMail)->limit(1);
			$query = $this->db->get();
			if ($query->num_rows() > 0)
			{
                $people_row = $query->row();
                $this->db->select('Alias');
                $this->db->from('contact_people');
                $this->db->join('contact_user_people', 'contact_user_people.people_id = contact_people.id');
                $this->db->join('contact_user', 'contact_user.uid = contact_user_people.user_id');
                $this->db->where('people_id', $people_row->id);
                $this->db->limit(1);
                $query = $this->db->get();
                if ($query->num_rows() > 0)
                {
                    $user_row = $query->row();
                    if (strcasecmp($alias, $user_row->Alias) == 0) {
                        $alias_match = "And your Alias and eMail match"; 
                    }else{
                        $alias_match = "But your Alias and eMail don't match";
                    }
                    $this->msg->setError('You already have an account.');
                    $this->msg->setMsg($alias_match);
                    $this->msg->setMsg('Try to login');
                    $this->tpl['countryOptions'] = $this->country_options();
                    $this->load->view('control_panel/register', $this->tpl);
                }
                else
                {
                    $this->pid = $people_row->id;
                    $this->db->from('places_timezone');
                    $this->db->join('places_country', 'places_country.ISO3166 = places_timezone.ISO3166');
                    $this->db->where('places_timezone.id', $this->validation->Country);
                    $query = $this->db->get();
                    $row = $query->row();
                    $this->FIPS = $row->FIPS;
                    $this->TZ = $row->TZ_Linux;

                    $this->msg->setError('Admin: Check This.');                    
                    $this->load->view('control_panel/register', $this->tpl);
                    
                    //$this->user_create();
                    //redirect('control_panel/person', 'location'); 
                }
            }
            else
            {
                $this->db->from('places_timezone');
                $this->db->join('places_country', 'places_country.ISO3166 = places_timezone.ISO3166');
                $this->db->where('places_timezone.TZ_Linux', $this->validation->Country);
                $query = $this->db->get();
                $row = $query->row();
                $this->FIPS = $row->FIPS;
                $this->TZ = $row->TZ_Linux;
                log_message('debug', "Control Panel->Registration->tz: ". $this->TZ);
                $this->user_create();

                redirect('control_panel/person', 'location');
            }
		}
	}
	
    
    function user_create()
    {
        $this->load->helper('string');

        $k = $this->activation_key = random_string('unique');
        $pass = random_string('alnum', 6);
        $ip = $this->fun->getip();
        $d = date("Y-m-d H:i:s");
        $a = $this->validation->Alias;
        $data = array(
                'Alias'     =>$a, 
                'Password'  =>$pass, 
                'timezone'  =>$this->TZ, 
                'IP'        =>$ip, 
                'activation_key'=>$k, 
                'added'     =>$d
            );
        if(!isset($this->pid))unset($data['people_id']);
        $this->db->insert('contact_user', $data);
        $this->uid = $this->db->insert_id();
        $data = array(
                'eMail'     =>  $this->validation->eMail,
                'Country'   =>  $this->FIPS,
            );
        $this->db->insert('contact_people', $data);
        $this->pid = $this->db->insert_id();            
        $data = array(
                'user_id'   =>  $this->uid,
                'people_id' =>  $this->pid,
            );
        $this->db->insert('contact_user_people', $data);

        $data = array(
                'uid'   =>  $this->uid,
                'Alias' =>  $this->validation->Alias
            );
        $this->session->unset_userdata('CTZ');
        $this->session->set_userdata($data);
        $this->ActivationEmail($this->validation->eMail, $pass);
    }

    function country_options()
	{
        $this->timetamer->setTZ();
        $time = time();
        $for= date('h:i A');
        $offset = date('O');
        $tzarray = $this->timetamer->offset_to_tz($offset);

		$output = '<select name="Country">';
		if( $tzarray !== false )
		{
            $output .= "<option value=\"\">-- Location for $for --</option>\n";
            foreach($tzarray as $v){
                $output .= "<option value=\"$v\">$v</option>\n";            	
            }
		}
		$output .= '</select>'; 
		return $output;		
	}


    function country_optionsOLD()
	{
		$output = '<select name="Country">';
        $time = time();
        $this->timetamer->setTZ();
        $for= date('h:i A');
        $tz= date('T');
        putenv('TZ=GMT');

		if( (isset($tz)) && ($tz != 'GMT') )
		{
            $output .= "<option value=\"\">-- Location for $for --</option>\n";
			$sql = "
			SELECT places_timezone.id, FIPS, TZ_Linux, Country 
			FROM places_timezone
			JOIN (places_country) 
			ON (places_timezone.ISO3166 = places_country.ISO3166)
			WHERE TZ = '$tz'
			";
		}
		else
		{
           $output .= "<option value=\"\">--Location by Timezone--</option>\n";
			$sql = "
			SELECT places_timezone.id, FIPS, TZ_Linux, Country 
			FROM places_timezone
			JOIN (places_country) 
			ON (places_timezone.ISO3166 = places_country.ISO3166)
			";
		}
		
		$query = $this->db->query($sql);
		foreach ($query->result() as $row)
		{
            $this->TZ_Linux = $row->TZ_Linux;
            $d['CTZ'][$row->id]['TZ_Linux'] = $row->TZ_Linux;
            $d['CTZ'][$row->id]['FIPS'] = $row->FIPS;
            $this->session->set_userdata($d);
            $l = strstr($row->TZ_Linux, '/');
            $c = $row->Country;
            $c = $c.$l;
            
            $output .= "<option value=\"$row->id\">$c</option>\n";
		}
		$output .= '</select>'; 
		return $output;		
	}


    private function ActivationEmail($email, $password)
    {
        $this->load->library('email');

        $this->email->from('NoReply@PzzAzz.com', 'PzzAzz LLC');
        $this->email->to($email);
        
        $this->email->subject('PzzAzz Account Activaten.');
        $host = $_SERVER['HTTP_HOST'];
        $message = 'Welcome to PzzAzz Mobile Billboard Advertising.';
        $message .= "\r\n\r\n";
        $message .= 'Your assigned password: '.$password;
        $message .= "\r\n\r\n";
        $message .= 'If you have received this mail in error you do not need to take any action to cancel the account. The account and all the information will be deleted from our server periodically, if no one logs in. You will not receive any further emails.';
        $message .= "\r\n\r\n";
        $message .= "Thank you for using $host";
        $message .= "\r\n\r\n";
        $message .= "This is a post-only mailing, replies to this email are not monitored or answered.";
        $message .= "\r\n";
        $message .= "We take your privacy serious, please report abuse to support at $host";

        $this->email->message($message);
        $this->email->attach(BASEPATH.'../img/logo.gif');
        $this->email->send();
        $this->msg->setMsg('Please check your email for your password');
        
    }

}
?>
